package com.xuan.mail.controller;

import com.xuan.mail.domin.Attachment;
import com.xuan.mail.service.AttachmentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("attachment")
public class AttachmentController {

    @Resource
    private AttachmentService attachmentService;

    @PostMapping("/upload")
    public Attachment upload(Integer emailId,@RequestPart("file") MultipartFile file) {
        try {
            Attachment attachment = attachmentService.upload(emailId,file);
            return attachment;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @PostMapping("/uploads")
    public List<Attachment> uploads(@RequestParam("emailId")Integer emailId,@RequestParam("files") MultipartFile[] files) {
       List<Attachment> attachments = new ArrayList<>();
       if (files != null && files.length > 0){
           for (MultipartFile file : files){
               try {
                   System.out.println("file name:"+file.getOriginalFilename());
                   Attachment attachment = attachmentService.upload(emailId,file);
                   attachments.add(attachment);
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
           return attachments;

       }else {
           return null;
       }

    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) {
        try {
            attachmentService.download(id, response);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载失败");
            // 处理异常，例如返回错误信息等
        }
    }
    //获得文件列表
    @GetMapping("/list/{emailId}")
    public List<Attachment> list(@PathVariable Integer emailId){

        return attachmentService.list(emailId);
    }
    //删除文件
    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Integer id){

           attachmentService.delete(id);
           return "删除成功";
    }

}
